package com.lsh.payment.core.service.wxpay.impl;

import com.lsh.payment.api.model.basevo.ExceptionStatus;
import com.lsh.payment.api.model.basevo.QueryContent;
import com.lsh.payment.core.constant.BusinessConstant;
import com.lsh.payment.core.model.payenum.PayStatus;
import com.lsh.payment.core.model.payment.PayDeal;
import com.lsh.payment.core.service.payment.IPayQueryChannelService;
import com.lsh.payment.core.service.payment.builder.QueryDirector;
import com.lsh.payment.core.service.payment.builder.WxQueryBuilder;
import com.lsh.payment.core.service.payment.impl.PayBaseService;
import com.lsh.payment.core.service.payment.impl.PayQueryBaseService;
import com.lsh.payment.core.strategy.vo.base.BasePayResponse;
import com.lsh.payment.core.strategy.query.QueryStrategyContext;
import com.lsh.payment.core.util.PayAssert;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.Map;

/**
 * Project Name: lsh-payment
 * Created by peter on 16/11/26.
 * 北京链商电子商务有限公司
 * Package
 * desc:
 */
@Service
@Transactional(readOnly = true)
public class WxQueryServiceImpl implements IPayQueryChannelService {

    private static Logger logger = LoggerFactory.getLogger(PayQueryBaseService.class);

    @Autowired
    private PayBaseService payBaseService;

    @Autowired
    private QueryStrategyContext context;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public QueryContent query(PayDeal payDeal) {
        Map<String, Object> params = new HashMap<>(7);

        params.put("channelId", payDeal.getChannelTransaction());
        params.put("out_trade_no", payDeal.getPayPaymentNo());
        params.put("pay_way", payDeal.getPayWay());
        params.put("system", payDeal.getSystem());

        BasePayResponse basePayResponse = context.queryPayStatusByParams(BusinessConstant.WECHATQUERY, params);

        //检查结果对象
        PayAssert.notNull(basePayResponse, ExceptionStatus.E2001013.getCode(), ExceptionStatus.E2001013.getMessage());

        WxQueryBuilder wxQueryBuilder = new WxQueryBuilder();
        QueryDirector director = new QueryDirector(wxQueryBuilder);
        director.queryParse(basePayResponse, payDeal);
        QueryContent content = wxQueryBuilder.getResult();

        if (content.getPayCode() != null) {
            int payCode = content.getPayCode();
            if (payCode == PayStatus.PAY_SUCCESS.getValue() || payCode == (PayStatus.PAY_FAIL.getValue())) {

                payBaseService.updPayDeal(wxQueryBuilder.getUpdatePaydeal(), payDeal);
            }
        }

        return content;
    }

}
